import json

from PyQt5.QtWidgets import (
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QHeaderView,
    QGridLayout,
    QPushButton,
    QFileDialog,
    QComboBox,
    QFrame,
    QGroupBox,
    QAbstractItemView,
    QTableWidgetItem,
    QTableWidget,
    QSpacerItem,
    QSizePolicy,
)
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QObject, QEvent
from PyQt5.QtGui import QPainter, QPen, QColor, QDoubleValidator
from pydantic import BaseModel, Field, field_validator
import gui.controls.envs as envs
from ..basic_grid_component import BasicGridComponent

# import gui.controls.envs as envs
from ..dlg_model_params import DlgModelParams
from ..c_params_table import CParamsTable
from ..dlg_params import DlgParams
from ..utils import Utils
from ..custom_widget import LineEditFloat, LineEditStr, LineEditInt, SelectBox
from ..util import util_material_key_map


class CustomTable(CParamsTable):

    def __init__(self, rows=0, columns=2, parent=None):
        super(CustomTable, self).__init__(rows=rows, columns=columns, parent=parent)
        self.setEditTriggers(QAbstractItemView.DoubleClicked)
        self.verticalHeader().setVisible(True)


class DlgHoneycombCore(DlgModelParams):
    honeycombCore_save_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super(DlgHoneycombCore, self).__init__(parent)
        self.setWindowTitle("蜂窝")
        self.setMinimumWidth(1200)
        self.setMinimumHeight(500)
        self.lastId = 0

        # 创建垂直布局
        layout = QHBoxLayout()
        self.widgetDict = {}

        self.data = [
            {"name": "name", "title": "名称/牌号", "type": "str", "require": True},
            {"name": "Density", "title": "密度", "type": "float"},
            {"name": "E1", "title": "E1", "type": "float"},
            {"name": "E2", "title": "E2", "type": "float"},
            {"name": "E3", "title": "E3", "type": "float"},
            {"name": "Nu12", "title": "Nu12", "type": "float"},
            {"name": "Nu13", "title": "Nu13", "type": "float"},
            {"name": "Nu23", "title": "Nu23", "type": "float"},
            {"name": "G12", "title": "G12", "type": "float"},
            {"name": "G13", "title": "G13", "type": "float"},
            {"name": "G23", "title": "G23", "type": "float"},
            {"name": "Sigma33", "title": "Sigma33", "type": "float"},
            {"name": "Sigma13", "title": "Sigma13", "type": "float"},
            {"name": "Sigma23", "title": "Sigma23", "type": "float"},
            # {"name": "id", "title": "id", "type": "float"},
        ]

        self.headerLabels = []
        self.headerValues = []
        for lab in self.data:
            self.headerLabels.append(lab.get("title"))
            self.headerValues.append(lab.get("name"))

        self.table = CParamsTable(rows=0, columns=len(self.headerLabels))
        self.table.cellDoubleClicked.connect(self.cell_was_double_clicked)
        self.table.setHorizontalHeaderLabels(self.headerLabels)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)
        # self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Interactive)
        # self.table.setColumnHidden(len(self.headerLabels) - 1, True)
        # self.table.horizontalHeader().setSectionResizeMode(
        #     0, QHeaderView.Fixed
        # )  # 第一列固定
        self.table.setColumnWidth(0, 160)
        # self.table.setColumnWidth(2, 90)
        layout.addWidget(self.table)
        addBtn = QPushButton("增加")
        editBtn = QPushButton("编辑")
        delBtn = QPushButton("删除")
        self.pBtnOK.setVisible(False)
        addBtn.setFocusPolicy(Qt.NoFocus)
        editBtn.setFocusPolicy(Qt.NoFocus)
        delBtn.setFocusPolicy(Qt.NoFocus)
        self.pBtnCancel.setFocusPolicy(Qt.NoFocus)

        self.btnLayout.insertWidget(1, addBtn)
        self.btnLayout.insertWidget(2, editBtn)
        self.btnLayout.insertWidget(3, delBtn)

        addBtn.clicked.connect(self.on_addBtn_clicked)
        delBtn.clicked.connect(self.on_delBtn_clicked)
        editBtn.clicked.connect(self.on_editBtn_clicked)

        self.vbox.insertLayout(0, layout)

    def init(self, data):
        self.loadTableData(data, self.table)

    def on_addBtn_clicked(self):
        row_count = self.table.rowCount()
        other = {"existName": self.getExistName(self.table)}
        self.dlg = DlgParams(
            self,
            type="add",
            data=self.data,
            lastId=row_count,
            other=other,
            title="蜂窝",
        )
        self.dlg.save_signal.connect(self.save_signal)
        self.dlg.exec_()
        self.dlg = None

    def on_delBtn_clicked(self):
        self.table.deleteSelectedRow()
        self.saveData()

    def on_editBtn_clicked(self):
        other = {"existName": self.getExistName(self.table, isAlert=True)}
        data = self.table.editSelectedRow()
        if data:
            self.dlg = DlgParams(
                self, type="alert", data=self.data, initData=data, other=other
            )
            self.dlg.alert_signal.connect(self.alert_signal)
            self.dlg.exec_()
            self.dlg = None

    def save_signal(self, data):
        # self.lastId = data[len(data) - 1]
        self.table.addRow(data)
        self.saveData()

    def alert_signal(self, data):
        self.table.updateRowWithData(data)
        self.saveData()

    def cell_was_double_clicked(self, row, column):
        other = {"existName": self.getExistName(self.table, isAlert=True)}
        data = self.table.editSelectedRow()
        self.dlg = DlgParams(
            self, type="alert", data=self.data, initData=data, other=other
        )
        self.dlg.alert_signal.connect(self.alert_signal)
        self.dlg.exec_()
        self.dlg = None

    def loadTableData2(self, file, table):
        # table.setRowCount(0)
        # file = "data/ipimas/uis/honeycombCore.json"
        res = Utils.read_json(file)
        table.setRowCount(0)
        if res:
            titleMap = self.headerValues
            for row_data in res:
                row_data = util_material_key_map.convertKey(row_data, 0)
                values = []
                for title in titleMap:
                    values.append(row_data.get(title) or "")
                table.addRow(values)

    def loadTableData(self, res, table):
        # table.setRowCount(0)
        # file = "data/ipimas/uis/honeycombCore.json"
        # res = Utils.read_json(file)
        table.setRowCount(0)
        if res:
            titleMap = self.headerValues
            for row_data in res:
                row_data = util_material_key_map.convertKey(row_data, 0)
                values = []
                for title in titleMap:
                    values.append(row_data.get(title) or "")
                table.addRow(values)
        # if "lastId" in res and res.get("lastId"):
        #     self.lastId = float(res.get("lastId"))

    def saveData(self):
        data = []
        for i in range(self.table.rowCount()):
            row_dict = {}
            for j in range(self.table.columnCount()):
                item = self.table.item(i, j)
                if item:
                    if j == 0:
                        row_dict["name"] = item.text()
                    else:
                        row_dict[self.headerValues[j]] = (
                            float(item.text()) if item.text() else None
                        )
                else:
                    row_dict[self.headerValues[j]] = None
                row_dict["type"] = "Honeycomb"
                row_dict = util_material_key_map.convertKey(row_dict, 1)
            data.append(row_dict)
        file = "data/ipimas/uis/honeycombCore.json"
        # data = util_material_key_map.convertKey(data, 1)
        # res = {"data": data, "lastId": self.lastId}
        Utils.write_json(file, data)
        # filtered_data = [{k: v for k, v in item.items() if k != "id"} for item in data]
        self.honeycombCore_save_signal.emit(data)
        if hasattr(envs, "ipimas_updateMaterialLibrary"):
            envs.ipimas_updateMaterialLibrary()

    def getExistName(self, table, isAlert=False):
        first_column_data = []
        row_index = -1
        selected_items = self.table.selectedItems()
        if selected_items and isAlert:
            row_index = selected_items[0].row()
        for i in range(table.rowCount()):
            if i == row_index:
                continue
            item = table.item(i, 0)  # 获取第一列的单元格项
            first_column_data.append(item.text())  # 添加文本到列表
        return first_column_data

    def closeEvent(self, event):
        DlgHoneycombCore._shown = False  # 使用类名访问类属性
        DlgHoneycombCore._instance = None  # 清除实例引用
        event.accept()
